import { Controller, Post, Get, Param, UseGuards, Request, Delete, Put } from '@nestjs/common';
import { ProjectShareService } from './project-share.service';
import { ProjectService } from './project.service';
import { UserService } from '../user/user.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../auth/roles.guard';

@Controller('project-shares')
export class ProjectShareController {
  constructor(
    private readonly projectShareService: ProjectShareService,
    private readonly projectService: ProjectService,
    private readonly userService: UserService,
  ) {}

  @UseGuards(JwtAuthGuard)
  @Post('project/:projectId')
  async createShare(@Param('projectId') projectId: string, @Request() req) {
    const user = await this.userService.findById(req.user.userId);
    if (!user) {
      throw new Error('User not found');
    }

    const project = await this.projectService.findOne(parseInt(projectId, 10));
    if (!project) {
      throw new Error('Project not found');
    }

    return this.projectShareService.createShare(project, user);
  }

  @UseGuards(JwtAuthGuard)
  @Get('my-shares')
  async getMyShares(@Request() req) {
    const user = await this.userService.findById(req.user.userId);
    if (!user) {
      throw new Error('User not found');
    }

    return this.projectShareService.findByUser(user);
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Get('project/:projectId')
  async getProjectShares(@Param('projectId') projectId: string, @Request() req) {
    const project = await this.projectService.findOne(parseInt(projectId, 10));
    if (!project) {
      throw new Error('Project not found');
    }

    // 设置资源所有者ID用于RolesGuard检查
    req.resourceOwnerId = project.owner.id;

    return this.projectShareService.findByProject(project);
  }

  @Get('token/:shareToken')
  async getShareByToken(@Param('shareToken') shareToken: string) {
    const share = await this.projectShareService.findByShareToken(shareToken);
    if (!share) {
      throw new Error('Share not found or inactive');
    }
    return share;
  }

  @UseGuards(JwtAuthGuard)
  @Delete(':id')
  async deactivateShare(@Param('id') id: string, @Request() req) {
    // 这里可以添加权限检查，确保只有分享者或项目所有者可以停用分享
    await this.projectShareService.deactivateShare(parseInt(id, 10));
    return { message: 'Share deactivated successfully' };
  }

  @UseGuards(JwtAuthGuard)
  @Put(':id/reactivate')
  async reactivateShare(@Param('id') id: string, @Request() req) {
    // 这里可以添加权限检查，确保只有分享者或项目所有者可以重新激活分享
    await this.projectShareService.reactivateShare(parseInt(id, 10));
    return { message: 'Share reactivated successfully' };
  }
}